<template>
  <div class="app-contanier" :class="$isMobile ? '' : 'pc-container'">
    <div class="info-content">
      <div class="live-info">
        <div class="live-title">{{ liveForm.title }}</div>
        <div class="live-time">
          <div class="time">
            <div class="time-hs">{{ liveForm.startHm }}</div>
            <div class="time-date">{{ liveForm.startYmd }}</div>
          </div>
          <div class="time-line">
            <div class="state">
              <span
                :class="
                  liveForm.liveState === '0'
                    ? 'no-start'
                    : liveForm.liveState === '3'
                    ? ''
                    : 'has-start'
                "
                >{{ LIVE_STATE[liveForm.liveState] || "" }}</span
              >
            </div>
            <div class="time-duration">
              <div class="duration-line"></div>
              <div class="duration">
                {{ TIME_COLOBJ[liveForm.durationTime] }}
              </div>
              <div class="duration-line"></div>
            </div>
          </div>
          <div class="time">
            <div class="time-hs">{{ liveForm.endHm }}</div>
            <div class="time-date">{{ liveForm.endYmd }}</div>
          </div>
        </div>
        <div class="cell-item">
          <div class="label">直播号</div>
          <div class="desc">{{ liveForm.meetingRoomNumber }}</div>
          <i
            class="sdlive icon-fuzhi icon"
            :data-clipboard-text="`${liveForm.meetingRoomNumber}`"
            @click="($event) => Copy($event, liveForm.meetingRoomNumber)"
          ></i>
        </div>
        <div class="cell-item">
          <div class="label">主讲人</div>
          <div class="desc">{{ liveForm.speaker || liveForm.userName }}</div>
        </div>
        <div class="cell-item" v-if="isMineLive">
          <div class="label">密码</div>
          <div class="desc">{{ liveForm.meetingPassword }}</div>
        </div>
        <div class="cell-item" v-if="isMineLive && liveForm.controlPassword">
          <div class="label">主持密码</div>
          <div class="desc">{{ liveForm.controlPassword }}</div>
        </div>
        <div class="cell-item" v-if="location">
          <div class="label">地点</div>
          <div class="desc">{{ liveForm.location }}</div>
        </div>
      </div>
      <div v-if="liveForm.briefIntroduction" class="live-desc">
        <div class="cell-item">
          <div class="label">简介</div>
        </div>
        <div class="msg">{{ liveForm.briefIntroduction }}</div>
      </div>
    </div>
    <div class="info-btns" v-if="liveForm.id">
      <van-button
        type="primary"
        block
        @click="goBack"
        v-if="liveForm.liveState === '3'"
      >
        返回
      </van-button>
      <van-button type="primary" block @click="intoLive" v-else>{{
        isMineLive ? "开始直播" : "观看直播"
      }}</van-button>
    </div>

    <div class="video-operate">
      <!--不是我的可以点赞收藏-->
      <template v-if="!isMineLive">
        <div class="info round-btn like next">
          <van-icon
            :class-prefix="`sdlive ${
              isLike ? 'icon-dianzan_kuai' : 'icon-dianzan'
            }`"
            @click="likeItem"
          />
        </div>
        <div class="info round-btn collect next">
          <van-icon
            :class-prefix="`sdlive ${isCollect ? 'icon-sc-active' : 'icon-sc'}`"
            @click="collectItem"
          />
        </div>
      </template>
      <template v-if="canEdit">
        <!--编辑直播-->
        <div class="info round-btn">
          <van-icon name="edit" @click="editLive" />
        </div>
      </template>
      <!--分享直播-->
      <div class="info round-btn share next" v-if="liveForm.id">
        <van-icon
          class-prefix="sdlive icon-share-s"
          @click="wxShareLiveMessage"
        />
      </div>
    </div>
  </div>

  <!--密码验证-->
  <InputPwd
    ref="inputPwdRef"
    :password="liveForm.meetingPassword"
    @pass="toDetail"
  />
</template>

<script setup>
import { ref, computed, onBeforeUnmount, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import dayjs from 'dayjs'
import { isJSON } from 'class-validator'

import InputPwd from '@/components/input-pwd.vue'

import { useAuthStore } from '@/store/auth'

import { TIME_COLOBJ, LIVE_STATE } from '@/source/index'

import Copy from '@/utils/clipboard'
import { VantMessage } from '@/utils/vant-utils'
import { WEB_HREF } from '@/utils/index'
import { wxShare, wxSdLiveApp } from '@/utils/wx'
import { sm2Decrypt } from '@/utils/sm2'

import {
  getInfo,
  likeCheck,
  collectCheck,
  likeLive,
  collectLive
} from '@/api/live'

const $router = useRouter()
const $route = useRoute()
const authStore = useAuthStore()

const liveForm = ref({})

const inputPwdRef = ref(null)

// 是否为我的直播
const isMineLive = ref(false)
// 未开始的直播可再次编辑
const canEdit = computed(
  () => isMineLive.value && liveForm.value.liveState === '0'
)

const isLike = ref(false)
const isCollect = ref(false)

const likeDisable = ref(false)
const collectDisable = ref(false)

let socket = null

// 进入直播
const intoLive = () => {
  // TODO: 是否主讲人 如果是主讲人拉起山东视频会议
  if (isMineLive.value) {
    // 如果已经开始， 不再能开启
    if (liveForm.value.liveState === '1') {
      VantMessage.warning('直播已开始')
      return
    }
    wxSdLiveApp(liveForm.value.id)
  } else {
    // TODO: 验证码
    if (inputPwdRef.value) {
      inputPwdRef.value.toShowDialog(true)
    }
  }
}

// 进入直播
const toDetail = () => {
  $router.push({
    path: '/live-detail',
    query: {
      id: liveForm.value.id,
      pass: '1'
    }
  })
}

// 点击进入编辑
const editLive = () => {
  $router.push({
    path: '/edit',
    query: {
      id: liveForm.value.id
    }
  })
}

// 后退
const goBack = () => {
  history.go(-1)
}

// 获取直播详情
const getLiveInfo = async() => {
  try {
    const id = $route.query && $route.query.id
    if (!id) {
      return
    }
    const res = await getInfo(id)
    if (res.data) {
      const info = res.data
      const startTime = info.startTime
      const endTime = info.endTime
      liveForm.value = {
        ...info,
        meetingPassword: info.meetingPassword
          ? sm2Decrypt(info.meetingPassword)
          : '',
        controlPassword: info.controlPassword
          ? sm2Decrypt(info.controlPassword)
          : '',
        startYmd: dayjs(startTime).format('YYYY年MM月DD日'),
        startHm: dayjs(startTime).format('HH:mm'),
        endYmd: dayjs(endTime).format('YYYY年MM月DD日'),
        endHm: dayjs(endTime).format('HH:mm')
      }
      // FIXME: 开发环境打开 是否是本人的直播
      isMineLive.value =
        process.env.NODE_ENV === 'development'
          ? false
          : authStore.userId === res.data.userId
      // 非结束刷新状态
      if (info.liveState !== '3') {
        refreshLive()
      }
      getLiveLC(id)
    } else {
      // FIXME:直播不存在后，向后退
      VantMessage.error('直播不存在')
      $router.go(-1)
    }
  } catch (error) {
    VantMessage.error('获取直播详情失败')
  }
}

const refreshLive = () => {
  if (!liveForm.value.liveId) {
    return
  }
  socket = new WebSocket(
    `${window.env.VUE_APP_STATE_SCOKET}/${liveForm.value.liveId}?userId=${authStore.userId}`
  )
  socket.onopen = () => {
    console.log('已经打开msg')
  }
  socket.onmessage = (res) => {
    if (!isJSON(res.data)) {
      return
    }
    const msg = JSON.parse(res.data)
    if (!(msg && msg.liveId && msg.liveId === liveForm.value.liveId)) {
      return
    }
    const type = msg.type
    // 状态
    if (type === 'state') {
      liveForm.value = {
        ...liveForm.value,
        liveState: msg.liveState
      }
    }
  }
  socket.onerror = (err) => {
    console.log('socket err', err)
  }

  socket.onclose = () => {
    console.log('info 长链接关闭')
  }
}

// 获取直播的点赞收藏
const getLiveLC = async(id) => {
  try {
    // 获取当前用户是否点赞
    const checkLike = await likeCheck(id)
    const checkCollect = await collectCheck(id)
    isLike.value = checkLike.data || false
    isCollect.value = checkCollect.data || false
  } catch (error) {
    VantMessage.error('网络异常')
  }
}
// 点赞
const likeItem = async() => {
  if (!liveForm.value.id) {
    return
  }
  try {
    isLike.value = !isLike.value
    if (likeDisable.value) {
      return
    }
    // 点赞程序
    likeDisable.value = true
    // 直播
    await likeLive(liveForm.value.id, !isLike.value)
    likeDisable.value = false
  } catch (error) {
    likeDisable.value = false
    VantMessage.error('点赞失败')
  }
}

// 收藏
const collectItem = async() => {
  if (!liveForm.value.id) {
    return
  }
  try {
    isCollect.value = !isCollect.value
    if (collectDisable.value) {
      return
    }
    // 收藏数据
    collectDisable.value = true
    await collectLive(liveForm.value.id, !isCollect.value)
    collectDisable.value = false
  } catch (error) {
    collectDisable.value = false
    VantMessage.error('收藏失败')
  }
}

async function wxShareLiveMessage() {
  wxShare(
    {
      title: liveForm.value.title,
      desc: liveForm.value.briefIntroduction,
      link: `${WEB_HREF}/info?id=${liveForm.value.id}`
    },
    true,
    (res) => {
      console.log('分享成功 >>>', res)
    }
  )
}

const review = () => {
  console.log('页面重现 visibilityState >>>', document.visibilityState)
  if (document.visibilityState === 'visible') {
    if (socket) {
      socket.close()
      socket = null
    }
    getLiveInfo()
  } else {
    if (socket) {
      socket.close()
      socket = null
    }
  }
}

onMounted(() => {
  // TODO: 直播
  getLiveInfo()
  // visibilitychange
  document.addEventListener('visibilitychange', review)
})

onBeforeUnmount(() => {
  if (socket) {
    socket.close()
    socket = null
  }
  // 清除事件
  document.removeEventListener('visibilitychange', review)
})
</script>

<style lang="less" scoped src="@/styles/info.less"></style>
